import 'package:flutter/material.dart';
import 'package:graphql_flutter/graphql_flutter.dart';
import 'package:labcloud_app/api/graphql/product_gql.dart';
import 'package:labcloud_app/api/graphql/user_gql.dart';
import 'package:labcloud_app/data/product_ad.dart';

class ProductAdModel extends ChangeNotifier {
  List<ProductAD>? _productAdList = [];
  bool _isLoading = false;
  String? _errorMessage;

  List<ProductAD>? get productAdList => _productAdList;
  bool get isLoading => _isLoading;
  String? get errorMessage => _errorMessage;

  /// 加载广告数据
  Future<void> loadAds(BuildContext context) async {
    if (_isLoading) return;
    
    _isLoading = true;
    _errorMessage = null;
    notifyListeners();

    try {
      final client = GraphQLProvider.of(context).value;
      
      final result = await client.query(
        QueryOptions(
          document: gql(ProductGQL.fetchProductAds),
        ),
      );

      if (result.hasException) {
        _errorMessage = '加载广告失败: ${result.exception.toString()}';
      } else {
        // 解析GraphQL响应数据
        final List<dynamic> adList = result.data!['productAd']['advertisingList'];
        _productAdList = adList.map((item) => ProductAD.fromJson(item)).toList();
      }
    } catch (e) {
      _errorMessage = '加载广告失败: $e';
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 添加商品到购物车
  Future<void> addToCart(BuildContext context, int productId, int quantity) async {
    try {
      final client = GraphQLProvider.of(context).value;
      
      final result = await client.mutate(
        MutationOptions(
          document: gql(UserGQL.fetchAddToCart),
          variables: {
            'productId': productId,
            'quantity': quantity,
          },
        ),
      );

      if (result.hasException) {
        // 错误处理留给调用者处理
        throw Exception('添加到购物车失败: ${result.exception.toString()}');
      } else {
        // 成功添加到购物车
        // 可以在这里添加其他逻辑，如更新购物车数量等
        notifyListeners();
      }
    } catch (e) {
      // 异常处理留给调用者处理
      throw Exception('添加到购物车失败: $e');
    }
  }

  /// 清除数据
  void clear() {
    _productAdList = null;
    _errorMessage = null;
    notifyListeners();
  }
}